<?php

namespace app\advertisement\logic;

use think\facade\Db;
use think\facade\Cache;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

use app\data\util\HttpUtil;
use app\common\library\Excel;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;

class AdvertisementCheckLogic
{
    public function __construct()
    {
        
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $createtime = $params['createtime'] ?? "";
        $status = $params['status'] ?? 0;

        $where = [];

        if (!empty($createtime)) {
            $where[] = ['stat_time', '>=', strtotime($createtime['0'])];
            $where[] = ['stat_time', '<=', strtotime($createtime['1']) + 3600*24-1];
        }else{
            // $yesterday = strtotime(date('Y-m-d', strtotime('-1 day') - timezone())); 
            // $where[] = ['stat_time', '>=', $yesterday];
            // $where[] = ['stat_time', '<=', $yesterday + 3600*24-1];
        }
        if (!empty($status)) {
            $where[] = ['status', '=', $status];
        }

        $list = Db::name('advertising_check')
            ->where($where)
            ->order('stat_time desc')
            ->paginate($limit);
        $lists = $list->items();
        
        foreach ($lists as $k=>$v) {
            switch ($v['status']) {
                case '0':
                    $lists[$k]['status'] = '校对中';
                    break;
                case '1':
                    $lists[$k]['status'] = '校对成功';
                    break;
                case '2':
                    $lists[$k]['status'] = '校对失败';
                    break;
                default:
                    $lists[$k]['status'] = '未知';
            }
        }
        
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @desc   import
     * @author zhagnheng
     * @date   2024-07-27
     */
    public function import($url){
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelDatas        = isset($data[0]) ? $data[0] : $data;
        if(!$excelDatas)    return json(DefaultResponse(201, false, '暂无数据!', null));
        
        $inserts = [];
        $stat_times = [];
        foreach($excelDatas as $v){
            if(empty($v['E'])) continue;
            $v['E'] = str_replace(['年', '月', '日'], ['-', '-', ' '], $v['E']);  
            $stat_time = strtotime($v['E']);
            if(!$stat_time) continue;
            $stat_times[$stat_time] = 1;
            $insert = [
                'stat_time' => $stat_time,
                'stat_time_day' => date('Y-m-d', $stat_time),
                'advertiser_id' => $v['A'],
                'platform' => $v['C'],
                'spend' => $v['D'],
            ];
            $inserts[] = $insert;
        }
        if(!empty($stat_times) && !empty($inserts)){
            $stat_times = array_keys($stat_times);
            $where[]  = ['stat_time', 'in', $stat_times];
            Db::name('advertising_check')->where($where)->delete();
            Db::name('advertising_checkinfo')->where($where)->delete();
            // halt($inserts);
            
            Db::name('advertising_checkinfo')->insertAll($inserts);

            $insert_infos = [];
            foreach ($stat_times as $ktime=>$vtime) {
                $insert_info = [
                    'stat_time' => $vtime,
                    'stat_time_day' => date('Y-m-d', $vtime),
                ];
                $insert_infos[] = $insert_info;
            }
            Db::name('advertising_check')->insertAll($insert_infos);
            //匹配规则
            $ReCheckinfos = Db::name('advertising_check')->where('status',0)->select()->toarray();
            foreach ($ReCheckinfos as $k=>$v) {
                $arr = $this->ReCheckinfo($v);
                Db::name('advertising_check')->where('id',$arr['id'])->update($arr);
            }
        }else{
            return json(DefaultResponse(201, false, '暂无导入数据!', null));
        }
        return json(DefaultResponse(200, false, '导入成功!', null));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function info($params = [])
    {
        $id = $params['id'] ?? "";
        if (empty($id)) {
            $data = [
                'list_official' => [],
                'list_api' => [],
            ];
            return json(DefaultResponse(200, true, '获取成功', $data));
        }
        $advertising_check = Db::name('advertising_check')->where('id',$id)->find();

        $where = [];

        if (!empty($advertising_check)) {
            $where[] = ['stat_time', '=', $advertising_check['stat_time']];
        }

        $list_official = Db::name('advertising_checkinfo')
            ->field('spend,advertiser_id,platform')
            ->where($where)
            ->order('spend desc')
            ->select()->toarray();
        $list_api = Db::name('advertising')
            ->field('spend,advertiser_id,platform_id as platform')
            ->where('type',0)
            ->where('spend',">",0)
            ->where($where)
            ->order('spend desc')
            ->select()->toarray();
        foreach ($list_api as $k=>$v) {
            switch ($v['platform']) {
                case '1':
                    $list_api[$k]['platform'] = 'Facebook';
                    break;
                case '2':
                    $list_api[$k]['platform'] = 'Google';
                    break;
                case '3':
                    $list_api[$k]['platform'] = 'TikTok';
                    break;
                default:
                    $list_api[$k]['platform'] = '未知';
            }
        }

        $data = [
            'list_official' => $list_official,
            'list_api' => $list_api,
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc ReCheck
     * @author zhangheng
     */
    public function ReCheck($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        if (empty($id)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $result = false;

        try {

            //具体查询
            $advertising_check = Db::name('advertising_check')->where('id',$id)->find();
            if (empty($advertising_check)) {
                return json(DefaultResponse(201, false, '数据不存在!', null));
            }
            $arr = $this->ReCheckinfo($advertising_check);
            $result = Db::name('advertising_check')->where('id',$arr['id'])->update($arr);
            
            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ReCheckinfo($advertising_check)
    {
        $spend_official_total = Db::name('advertising_checkinfo')
            ->field('SUM(spend) as spend')
            ->where('stat_time',$advertising_check['stat_time'])
            ->select()->toarray();

        $spend_api_total = Db::name('advertising')
            ->field('SUM(spend) as spend')
            ->where('type',0)
            ->where('stat_time',$advertising_check['stat_time'])
            ->select()->toarray();

        $spend_official_total = $spend_official_total ? $spend_official_total[0]['spend'] : 0;
        $spend_api_total = $spend_api_total ? $spend_api_total[0]['spend'] : 0;

        if($spend_official_total == $spend_api_total){
            $status = 1;
        }else{
            $status = 2;
        }
        $arr = [
            'id' => $advertising_check['id'],
            'status' => $status,
            'spend_official' => (float)$spend_official_total,
            'spend_api' => (float)$spend_api_total,
            'update_time' => time(),
        ];
        return $arr;
    }
    

}
